package com.anlogic.sdk.startup;

import java.io.IOException;

import org.apache.logging.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import com.anlogic.sdk.startup.utils.Utils;
import com.anlogic.sdk.utils.EnvUtils;
import com.anlogic.sdk.utils.LogUtils;
import com.anlogic.sdk.utils.StringUtils;
import com.anlogic.sdk.utils.UIUtils;

public class LicenseHandler extends AbstractHandler {
	private static Logger logger = LogUtils.getLogger(LicenseHandler.class);
	
	public static String[] licenseFilters = new String[] { "*.lic" };
	
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String msg = "IDE is valid until " + StringUtils.getDateFromString(Utils.getLicenseContent());;
		IProject[] projects = EnvUtils.getUnMatchedProjects();
		for (IProject proj : projects) {
			msg += " " + proj.getName();
		}
		MessageDialog.openInformation(null, "License", msg);
		return null;
	}

	public static boolean showErrorMessage(String msg) {
		Shell shell = UIUtils.getActiveShell();
		MessageDialog dialog = new MessageDialog(shell, "License Validation", null, msg, MessageDialog.ERROR, new String[] { "Choose New License", "Close" }, 0);
		int ret = dialog.open();
		if (ret == 0) {
			FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
			fileDialog.setFilterExtensions(licenseFilters);
			String result = fileDialog.open();
			if (result != null) {
				try {
					logger.info("Replace License...");
					Utils.replaceLicense(result);
				} catch (IOException e) {
					logger.error("Replace License Failed!");
				}
				logger.info("Replace License done");
				return validate();
			}
		}
		return false;
	}
	
	public static boolean validate() {
		String msg = "";
		if (!Utils.licenseExists()) {
			msg = "License doesen't exist!";
			return showErrorMessage(msg);
		}
		
		String ret = Utils.validate();
		if (ret.contains("License expired")) {
			msg = "License expired! Please choose new license!";
			return showErrorMessage(msg);
		} else if (ret.contains("Invalid License")) {
			msg = "Invalid License! Please choose new license!";
			return showErrorMessage(msg);
		} else if (ret.contains("success")) {
			logger.info("License validation success!");
		} else {
			msg = "License validation failed!";
			return showErrorMessage(msg);
		}
		return true;
	}
}
